package io.renren.modules.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.modules.device.dao.TDeviceDao;
import io.renren.modules.device.entity.TAlarmType;
import io.renren.modules.device.entity.TDeviceCategory;
import io.renren.modules.device.entity.TDeviceEntity;
import io.renren.modules.device.entity.vo.DeviceVO;
import io.renren.modules.device.service.TDeviceService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service("tDeviceService")
public class TDeviceServiceImpl extends ServiceImpl<TDeviceDao, TDeviceEntity> implements TDeviceService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        List<DeviceVO> deviceEntityList = new ArrayList<>();
        String categoryId = (String) params.get("categoryId");
        if (StringUtils.isEmpty(categoryId)) {
            categoryId = "1";
        }
        String key = (String) params.get("key");
        if (StringUtils.isEmpty(key)) {
            deviceEntityList = this.baseMapper.queryDevices(categoryId);
        } else {
            key = "%".concat(key).concat("%");
            deviceEntityList = this.baseMapper.queryDevicesByKeySearch(key, categoryId);
        }
        return new PageUtils(deviceEntityList, params);
    }

    @Override
    public DeviceVO getDeviceInfoById(String deviceId) {
        return this.baseMapper.getDeviceInfoById(deviceId);
    }

    @Override
    public List<TDeviceCategory> listCategories() {
        return this.baseMapper.listCategory();
    }

    @Override
    public TDeviceCategory categoryInfo(String categoryId) {
        return this.baseMapper.categoryInfo(categoryId);
    }

    @Override
    public List<TAlarmType> listAlarmTypes() {
        return this.baseMapper.listAlarmTypes();
    }

    @Override
    public boolean updateOnlineStatus(String deviceCode, boolean onlineStatus) {
//        TDeviceEntity entity = this.baseMapper.getDeviceInfoByCode(deviceCode);
//        entity.setStatus(onlineStatus ? 1 : 0);
        UpdateWrapper<TDeviceEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().set(TDeviceEntity::getStatus, onlineStatus ? 1 : 0)
                .eq(TDeviceEntity::getCode, deviceCode);

        return this.baseMapper.update(null, updateWrapper) > 0;
    }

}